package com.yanxibao.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yanxibao.bean.Collection;
import com.yanxibao.common.Result;
import com.yanxibao.dto.PageQueryDTO;
import com.yanxibao.mapper.CollectionMapper;
import com.yanxibao.mapper.UserinfoMapper;
import com.yanxibao.service.CollectionService;
import com.yanxibao.util.QueryUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 收藏;(_collection)表服务实现类
 *
 * @author kongke
 * @date 2023/11/16
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements CollectionService {

    @Resource
    private CollectionMapper collectionMapper;

    @Resource
    private UserinfoMapper userinfoMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param collectionId 主键
     */
    @Override
    public Result<Collection> queryById(Integer collectionId) {
        Collection collection = getById(collectionId);

        return collection != null ? Result.success(collection) : Result.error("06040", "未查询到数据");
    }

    /**
     * 分页查询
     *
     * @param collection 筛选条件
     * @param current    当前页码
     * @param size       每页大小
     */
    @Override
    public Result<PageQueryDTO<Collection>> pageQuery(Collection collection, Integer current, Integer size) {
        Page<Collection> page = Page.of(current, size);

        @SuppressWarnings("unchecked")
        PageQueryDTO<Collection> dto =
                (PageQueryDTO<Collection>) QueryUtil.FltQuery("eq", collection, page, collectionMapper, null);

        return Result.success(dto);
    }

    /**
     * 新增数据
     *
     * @param collection 实例对象
     * @return 实例对象
     */
    @Override
    public Result<Collection> insert(Collection collection) {

//        传入ID值则数据异常
        if (collection.getCollectionId() != null) {
            return Result.error("06060", "ID冲突");
        }

        boolean save = save(collection);
        userinfoMapper.addCol(collection.getUserId());
        return save ? Result.success(collection) : Result.error("06061", "新增数据失败");
    }


    /**
     * 通过主键删除数据
     *
     * @return 是否成功
     */
    @Override
    public Result<Boolean> deleteById(Integer colId) {
        boolean remove = removeById(colId);
        return remove ? Result.success(true) : Result.error("06020", "删除数据失败");
    }


    /**
     * 是否关注
     */
    @Override
    public Result<Boolean> isCol(String userId, Integer umId) {
        if (userId == null || umId == null) {
            return Result.error("06031", "参数错误");
        }
        Collection col = collectionMapper.isCol(userId, umId);
        return col != null ? Result.success(true) : Result.error("06030", "未关注");
    }
}